/**
 * @desc Loading API
 *  打开 Loading.show();
 *  隐藏 Loading.hide();
 */
import React from 'react';
import ReactDOM from 'react-dom';
import { Spin } from 'antd';
import { LoadingOutlined } from '@ant-design/icons';
import styleUser from './style/index.less';

const LoadingIndicator = <LoadingOutlined style={{ fontSize: 26, fontWeight: 'bold' }} spin />;

class LoadingDom extends React.Component {
  constructor() {
    super();
    this.state = {
      show: false,
      showNum: 0,
    };
  }

  // eslint-disable-next-line react/no-unused-class-component-methods
  hide = () => {
    let { showNum } = this.state;
    showNum -= 1;
    if (showNum <= 0) {
      this.setState({
        show: false,
        showNum: 0,
      });
    } else {
      this.setState({
        showNum,
      });
    }
  };

  // eslint-disable-next-line react/no-unused-class-component-methods
  show = () => {
    let { showNum } = this.state;
    showNum += 1;
    this.setState({
      show: true,
      showNum,
    });
  };

  render() {
    const { show } = this.state;
    return (
      <div className={`loading ${!show ? 'hide' : ''}`}>
        <Spin tip="数据加载中......" size="large" delay={500} indicator={LoadingIndicator} />
        <div className="mark" />
      </div>
    );
  }
}

let componentRef = '';
const createLoading = new Promise(() => {
  const div = document.createElement('div');
  div.className = 'souche--loading';
  document.body.appendChild(div);
  const component = React.createElement(LoadingDom, {
    ref: (ref) => {
      componentRef = ref;
    },
  });
  ReactDOM.render(component, div);
});
const Loading = {
  show: () => {
    if (!componentRef) {
      createLoading().then(() => {
        componentRef.show();
      });
    } else {
      componentRef.show();
    }
  },
  hide: () => {
    if (!componentRef) {
      console.error('未启用LOADING，请先使用show方法启用，再使用hide方法隐藏');
    } else {
      componentRef.hide();
    }
  },
};

export default Loading;
